package org.paic.d;

/**
 * @author kerry
 */
public class Dialect {
    /**
     * 查询总记录数返回的列的别名
     */
    public static final String RS_COLUMN = "NUMS";

    /**
     * 设置是否支持limit查询，Oracle是用rownum
     * 
     * @param limitSupport
     */
    public void setLimitSupport(boolean limitSupport) {
        this.limitSupport = limitSupport;
    }

    private boolean limitSupport = true;

    /**
     * 拼接分页查询sql
     * 
     * @param sql 查询sql
     * @param offset 开始查询的位移偏量
     * @param limit 要查询的记录数
     * @return 重新拼接好的sql
     */
    public String getPagiSql(String sql, int offset, int limit) {
        sql = sql.trim().toLowerCase();
        StringBuilder sb = new StringBuilder();
        if (!this.limitSupport) {
            sb.append("select * from (select xxx.*, rownum as rrr from (");
            sb.append(sql);
            sb.append(") xxx) ttt where ttt.rrr > ");
            sb.append(offset);
            sb.append(" and ttt.rrr <= ");
            sb.append(offset + limit);
        } else {
            sb.append("select ttt.* from (");
            sb.append(sql);
            sb.append(") ttt limit ");
            sb.append(offset);
            sb.append(",");
            sb.append(limit);
        }
        return sb.toString();
    }

    /**
     * 拼接查询总记录数的sql
     * 
     * @param sql 查询sql
     * @return 重新拼接好的sql
     */
    public String getCountSql(String sql) {
        sql = sql.trim().toLowerCase();
        StringBuilder sb = new StringBuilder();

        sb.append("select count(*) as ");
        sb.append(RS_COLUMN);
        sb.append(" from (");
        sb.append(sql);
        sb.append(") ttt");

        return sb.toString();
    }
}
